package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.ColorTagAdapter;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.DDictionary;
import com.isunland.managesystem.entity.DDictionaryDetailOriginal;
import com.isunland.managesystem.entity.ZTreeNode;
import com.isunland.managesystem.entity.ZTreeNodeListOriginal;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.CustomTextView;
import com.skydoves.colorpickerview.ColorPickerView;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/5/24 16:29
 */
public class ColorTagDialogFragment extends BaseDialogFragment {
  @BindView(R.id.cpv_tagColor) ColorPickerView cpvTagColor;
  @BindView(R.id.et_tagName) EditText etTagName;
  @BindView(R.id.btn_confirm) Button btnConfirm;
  @BindView(R.id.ctv_selectColor) CustomTextView ctvSelectColor;
  private ColorTagAdapter mAdapter;
  private AlertDialog mProgressDialog;
  private ArrayList<ZTreeNode> mList;
  private AlertDialog mDialog;
  private AlertDialog mDialogNewTag;

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {
    super.onCreateDialog(savedInstanceState);
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = mActivity.getLayoutInflater().inflate(R.layout.dialog_progress, null);
    builderSingle.setView(v);
    mProgressDialog = builderSingle.create();
    View viewNewTag = mActivity.getLayoutInflater().inflate(R.layout.dialog_label_update, null);
    ButterKnife.bind(this, viewNewTag);
    cpvTagColor.setColorListener(new ColorPickerView.ColorListener() {
      @Override public void onColorSelected(int color) {
        ctvSelectColor.setSolidColor(color);
      }
    });
    btnConfirm.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        volleyPostAddTag();
      }
    });

    mDialogNewTag = new AlertDialog.Builder(mActivity).setView(viewNewTag).create();
    mDialog = new AlertDialog.Builder(mActivity).setTitle("标签")
        .setAdapter(mAdapter, new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            ZTreeNode base = mAdapter.getItem(which);
            select(base);
          }
        })
        .setPositiveButton(R.string.createNewTag, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialog, int which) {
            mDialogNewTag.show();
          }
        })
        .create();
    volleyPost();
    return mProgressDialog;
  }

  private void select(ZTreeNode base) {
    if (getTargetFragment() == null) return;
    Intent i = new Intent();
    BaseParams<ZTreeNode> params = new BaseParams<>();
    params.setItem(base);
    i.putExtra(BaseFragment.EXTRA_PARAMS, params);
    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
    if (mDialogNewTag != null && mDialogNewTag.isShowing()) mDialogNewTag.dismiss();
  }

  private void volleyPostAddTag() {
    int color = cpvTagColor.getColor();
    String text = MyStringUtil.getText(etTagName);
    if (color == 0) {
      ToastUtil.show("请点击调色盘选择标签颜色");
      return;
    }

    if (MyStringUtil.isEmpty(text)) {
      ToastUtil.show("请输入标签名称");
      return;
    }
    if (text.length() > 7) {
      ToastUtil.show("标签不能超过6个字");
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_LABEL_ADD);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("extParam", String.format("#%06X", (0xFFFFFF & color)));
    params.put("name", text);
    params.put("topicKindCode", mBaseParams.getCode());
    params.put("topicKindName", mBaseParams.getName());
    params.put("isCommon", String.valueOf(0));
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {
        ToastUtil.show(
            MyStringUtil.connect(getString(R.string.createNewTag), getString(R.string.failure)));
      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        DDictionaryDetailOriginal original =
            new Gson().fromJson(json, DDictionaryDetailOriginal.class);
        ToastUtil.show(original.getMessage());
        if (original.getResult() == Base.SUCCESS) {
          DDictionary data = original.getData();
          ZTreeNode item = new ZTreeNode();
          item.setName(data.getRecordText());
          item.setExtParam(data.getRecordCode());
          select(item);
        }
      }
    });
  }

  @Override public void initData() {
    super.initData();
    mList = new ArrayList<>();
    mAdapter = new ColorTagAdapter(mActivity, mList);
  }

  private void volleyPost() {
    String url = ApiConst.getAbsoluteUrl(getUrl());
    HashMap<String, String> params = getparameters();
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String json) throws JSONException {

        mProgressDialog.dismiss();
        mDialog.show();
        ArrayList<ZTreeNode> list =
            new Gson().fromJson(json, ZTreeNodeListOriginal.class).getRows();
        mList.clear();
        mList.addAll(list);
        mAdapter.notifyDataSetChanged();
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    });
  }

  /**
   * 获取参数列表
   */
  public HashMap<String, String> getparameters() {

    return new ParamsNotEmpty().put("dictFlag", "diseaseGrade")
        .put("type", "mobile")
        .put("topicKindCode", mBaseParams.getCode())
        .put("topicKindName", mBaseParams.getName())
        .getParams();
  }

  public String getUrl() {
    return ApiConst.URL_QUERY_LIST_PROJECT_TYPE_TREE_V293;
  }
}
